package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.result.R;
import com.atguigu.yygh.user.properties.ConstantWxProperties;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.atguigu.yygh.user.utils.HttpUtils;
import com.atguigu.yygh.utils.JwtHelper;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/3/20 17:24
 */
@Controller
@RequestMapping("/api/userinfo/wx")
public class WxApiController {
    @Autowired
    private ConstantWxProperties wxProperties;
    @Autowired
    private UserInfoService userInfoService;
    //获取微信登录二维码参数
    @GetMapping("/getWxLoginParam")
    @ResponseBody
    public R getWxLoginParam() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", wxProperties.getAppid());
        map.put("scope","snsapi_login");
        map.put("redirect_uri", wxProperties.getRedirectUrl());
        map.put("state",System.currentTimeMillis()+"");
        map.put("style","black");
        return R.ok().data(map);
    }
    //微信登录回调
    @GetMapping("/callback")
    public String callback(String code,String state) throws Exception {
        //第一步 获取临时票据 code
        //第二步 拿着code和微信id和秘钥，请求微信固定地址 ，得到两个值     openid 和 session_key
        //请求微信固定地址https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl  = String.format(stringBuilder.toString(), wxProperties.getAppid(), wxProperties.getSecret(), code);
        //使用httpclient请求这个地址，得到返回结果
        String accesstokenInfo  = HttpClientUtils.get(accessTokenUrl);
        //得到返回结果，转成jsonObj
        JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
        //得到openid
        String openid = jsonObject.getString("openid");
        //得到access_token
        String access_token = jsonObject.getString("access_token");
        //判断数据库是否存在微信的扫描人信息
        UserInfo userByOpenid =userInfoService.selectWxUserByOpenid(openid);
        if (userByOpenid == null){
            //如果不存在,第一次wx登录，拿着openid 和 access_token请求微信地址，得到扫描人信息
            //请求微信地址https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
            StringBuilder stringBuilder1 = new StringBuilder();
            stringBuilder1.append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                   .append("&openid=%s");
            String userInfoUrl  = String.format(stringBuilder1.toString(), access_token, openid);
            //使用httpclient请求这个地址，得到返回结果
            String userInfoFromWx = HttpClientUtils.get(userInfoUrl);
            //得到返回结果，转成jsonObj
            JSONObject userInfoJsonObject = JSONObject.parseObject(userInfoFromWx);
            //得到扫描人信息
            String nickName = userInfoJsonObject.getString("nickname");
            String headImgUrl = userInfoJsonObject.getString("headimgurl");
            //保存扫描人信息到数据库-userByOpenid为null时
            userByOpenid = new UserInfo();
            //第一次登录，默认设置为1
            userByOpenid.setStatus(1);
            userByOpenid.setNickName(nickName);
            userByOpenid.setOpenid(openid);
            userInfoService.save(userByOpenid);
        }
        //返回name和token
        HashMap<String, String> map = new HashMap<>();
        String name = userByOpenid.getName();
        if (StringUtils.isEmpty(name)){
            name=userByOpenid.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name=userByOpenid.getOpenid();
        }
        map.put("name", name);
        //判断userInfo是否有手机号，如果手机号为空，返回openid
        //如果手机号不为空，返回openid值是空字符串
        //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
        if (StringUtils.isEmpty(userByOpenid.getPhone())){
            map.put("openid", openid);
        }else {
            map.put("openid","");
        }
        //返回token
        String token = JwtHelper.createToken(userByOpenid.getId(), name);
        map.put("token", token);
        //跳转到前端页面
        return "redirect:http://localhost:4093/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
    }
}

